package cn.xspace.app.filemg.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.Toast;

import com.xspace.android.xafcommon.db.dbsub.BaseDbMg;
import com.xspace.android.xafcommon.util.BaseRProxy;
import com.xspace.android.xafcommon.util.DateUtils;
import com.xspace.android.xafcommon.util.LogUtil;
import com.xspace.android.xafcommon.util.StringUtils;

import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import cn.xspace.app.filemg.bean.ChooseFileInfo;
import cn.xspace.app.filemg.bean.FileInfo;
import cn.xspace.app.filemg.bean.ImgPackInfo;
import cn.xspace.app.filemg.util.CallBack;
import cn.xspace.app.filemg.util.FileInfoCompare;
import cn.xspace.app.filemg.util.FileMg;
import cn.xspace.app.filemg.view.FileAppAdapter;


public class FileAppFragment extends Fragment implements CallBack{
	private Context mContext;
	private ExpandableListView mGridView;
	private FileAppAdapter mFileAppAdapter;
	private ArrayList<ImgPackInfo> gridList = new ArrayList<ImgPackInfo>();
	private boolean checkFlag;
	private static CallBack mCallBack;
	private boolean isOver = false;
	List<ResolveInfo> mAllApps = new ArrayList<ResolveInfo>();
	List<PackageInfo> mAllPackages = new ArrayList<PackageInfo>();
	PackageManager packageManager = null;
	private ArrayList<FileInfo> tallAplList = new ArrayList<FileInfo>();
	private ArrayList<FileInfo> unInstallAplList = new ArrayList<FileInfo>();
	private MyAsyncTask mMyAsyncTask;
	public HashMap<String, String> instailMap = new HashMap<String, String>();
	private ChooseFileInfo chooseInfo = new ChooseFileInfo();

	public static FileAppFragment newInstance(CallBack callBack) {
		FileAppFragment newFragment = new FileAppFragment();
		mCallBack = callBack;
		return newFragment;

	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				if (mFileAppAdapter != null) {
					try {
						mFileAppAdapter.notifyDataSetChanged();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}else{
					mFileAppAdapter = new FileAppAdapter(mContext, gridList,FileAppFragment.this);
					mGridView.setAdapter(mFileAppAdapter);
				}
				break;
			case 1:
				if (mGridView != null)
					try {
						mGridView.expandGroup(0);
					} catch (Exception e) {
						e.printStackTrace();
					}
				break;

			default:
				break;
			}
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = FileAppFragment.this.getActivity();
		packageManager = mContext.getPackageManager();
		tallAplList = BaseDbMg.getInstance().getFileMgDb().querySend("apk");
	}

	private class MyAsyncTask extends AsyncTask {
		@Override
		protected Object doInBackground(Object... arg0) {
			// TODO Auto-generated method stub
			setMyAllApps();
			// apkIoc();
			return null;
		}

		@Override
		protected void onPreExecute() {

		}

		@Override
		protected void onPostExecute(Object result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			// handler.sendEmptyMessage(1);
			// BaseDbMg.getInstance().getSendSql().saveOrUpdate("apk",
			// gridList);
		}

	}

	private void apkIoc() {
		for (FileInfo info : tallAplList) {
			try {
				PackageManager pm = getActivity().getPackageManager();
				PackageInfo apkInfo = pm.getPackageArchiveInfo(info.getPath(),
						PackageManager.GET_ACTIVITIES);
				if (apkInfo != null) {
					ApplicationInfo appInfo = apkInfo.applicationInfo;
					//String appName = pm.getApplicationLabel(appInfo).toString();
					String packageName = appInfo.packageName;
					if (StringUtils.isNull(instailMap.get(packageName))) {
						info.setPackageName(packageName);
						instailMap.put(packageName, packageName);
						//info.setApkIoc(pm.getApplicationLogo(appInfo));
						if(null==info.getApkIoc()){
							info.setApkIoc(pm.getApplicationIcon(appInfo));
						}
						try {
							for (FileInfo cInfo : chooseInfo.getFileList()) {
								if (cInfo.getPath().equals(info.getPath())) {
									info.setCheckFlag(true);
								}
							}
						} catch (Exception e) {
							System.out.println("------------------apkInfo:"
									+ e.getMessage());
							e.printStackTrace();
						}
						//ApplicationInfo minfo=showUninstallAPKIcon(info.getPath());
						//info.setApkIoc( getResources().getDrawable(minfo.icon));
						unInstallAplList.add(info);
						handler.sendEmptyMessage(0);
					}
				}
			} catch (Exception e) {
				System.out.println("------------------apkInfo:"
						+ e.getMessage());
			}
		}
	}

	private void seetMyUnInstallApps() {
		if (tallAplList != null && tallAplList.size() > 0) {
//			ArrayList<FileInfo> tallAplListTest = new ArrayList<FileInfo>();
//			for( FileInfo apkInfo:gridList.get(0).getImgList()){
//				for(FileInfo apkInfo1:tallAplList){
//					if(apkInfo.getPath().equals(apkInfo1.getPath())){
//						tallAplListTest.add(apkInfo1);	
//					}
//				}
//			}
//			System.out.println("------------------tallAplListTest:"
//					+ tallAplListTest.size());
//			tallAplList.remove(tallAplListTest);
//			if(tallAplList.size()>0){
			ImgPackInfo pInfo = new ImgPackInfo();
			pInfo.setPackName("未安装");
			pInfo.setImgList(unInstallAplList);
			gridList.add(pInfo);
//			}
			handler.sendEmptyMessage(0);
			handler.sendEmptyMessage(1);
			apkIoc();
		}else{
			handler.sendEmptyMessage(0);
			handler.sendEmptyMessage(1);
		}
	}

	public void setMyAllApps() {
		// 查找所有首先显示的activity
		Intent intent = new Intent(Intent.ACTION_MAIN, null);
		intent.addCategory(Intent.CATEGORY_LAUNCHER);
		//mAllApps = packageManager.queryIntentActivities(intent, 0);
		mAllPackages = packageManager.getInstalledPackages(0);
		ArrayList<FileInfo> childList = new ArrayList<FileInfo>();
		ImgPackInfo pInfo = new ImgPackInfo();
		pInfo.setPackName("已安装");
		pInfo.setImgList(childList);
		gridList.add(pInfo);
		for (int i = 0; i < mAllPackages.size(); i++) {
			// ResolveInfo resolveInfo = mAllApps.get(i);
			PackageInfo packageInfo = mAllPackages.get(i);
			String name = packageInfo.applicationInfo.loadLabel(packageManager)
					.toString();
			//LogUtil.v("fileAppFrag", "sys app name:" + name+ packageInfo.applicationInfo.flags);
			if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) {
				// 第三方应用
				FileInfo info = new FileInfo();
				info.setFileType("apk");
				info.setTime(DateUtils.timeMillisToDateTimeString(
						packageInfo.lastUpdateTime, DateUtils.FORMAT_5));
				// info.setApkIoc(resolveInfo.loadIcon(packageManager));
				info.setApkIoc(packageInfo.applicationInfo
						.loadIcon(packageManager));
				info.setName(packageInfo.applicationInfo.loadLabel(
						packageManager).toString());
				// info.setName(resolveInfo.loadLabel(packageManager).toString());
				info.setPath(packageInfo.applicationInfo.sourceDir);
				info.setPackageName(packageInfo.packageName);
				File sourceFile = new File(info.getPath());
				info.setSize(FileMg.getFileSizes(sourceFile));
				try {
					for (FileInfo cInfo : chooseInfo.getFileList()) {
						if (cInfo.getPath().equals(info.getPath())) {
							info.setCheckFlag(true);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				childList.add(info);
				instailMap.put(info.getPackageName(), info.getPackageName());
			}
		}
		// 按照名字排序
		Collections.sort(childList, new FileInfoCompare());
		seetMyUnInstallApps();

	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		handler.removeMessages(0);
		handler.removeMessages(1);
		gridList.clear();
		super.onDestroy();
	}

	public void initChooseData(ChooseFileInfo chooseInfo) {
		this.chooseInfo = chooseInfo;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(BaseRProxy.file_app, container, false);
		mGridView = (ExpandableListView) view
				.findViewById(BaseRProxy.favorite_webs_list_expandlv);
		if(gridList.size()==0){
			mMyAsyncTask = new MyAsyncTask();
			mMyAsyncTask.execute();
		}else{
			mFileAppAdapter = new FileAppAdapter(mContext, gridList,FileAppFragment.this);
			mGridView.setAdapter(mFileAppAdapter);
		}

		return view;

	}

	@Override
	public void checkedInfo(FileInfo info) {
		// TODO Auto-generated method stub
		info.setCheckFlag(!info.isCheckFlag());
		if (info.isCheckFlag()) {
			if (chooseInfo.getFileList().size() >= 10) {
				info.setCheckFlag(!info.isCheckFlag());
				Toast.makeText(getActivity(), "最多能选10个文件",
						Toast.LENGTH_SHORT).show();
			}
			if ((chooseInfo.getSize() + info.getSize()) > (1048576 * 100)) {
				info.setCheckFlag(!info.isCheckFlag());
				Toast.makeText(getActivity(), "所选文件已超过100MB",
						Toast.LENGTH_SHORT).show();
			}
		}
		mFileAppAdapter.notifyDataSetChanged();
		mCallBack.checkedInfo(info);
	}
	private  ApplicationInfo  showUninstallAPKIcon(String apkPath) {  
        String PATH_PackageParser = "android.content.pm.PackageParser";  
        String PATH_AssetManager = "android.content.res.AssetManager";
        ApplicationInfo info=null;
        try {  
            // apk包的文件路径  
            // 这是一个Package 解释器, 是隐藏的  
            // 构造函数的参数只有一个, apk文件的路径  
            // PackageParser packageParser = new PackageParser(apkPath);  
            Class pkgParserCls = Class.forName(PATH_PackageParser);  
            Class[] typeArgs = new Class[1];  
            typeArgs[0] = String.class;  
            Constructor pkgParserCt = pkgParserCls.getConstructor(typeArgs);  
            Object[] valueArgs = new Object[1];  
            valueArgs[0] = apkPath;  
            Object pkgParser = pkgParserCt.newInstance(valueArgs);  
            LogUtil.d("fileAppFrag", "pkgParser:" + pkgParser.toString());  
            // 这个是与显示有关的, 里面涉及到一些像素显示等等, 我们使用默认的情况  
            DisplayMetrics metrics = new DisplayMetrics();  
            metrics.setToDefaults();  
            // PackageParser.Package mPkgInfo = packageParser.parsePackage(new  
            // File(apkPath), apkPath,  
            // metrics, 0);  
            typeArgs = new Class[4];  
            typeArgs[0] = File.class;  
            typeArgs[1] = String.class;  
            typeArgs[2] = DisplayMetrics.class;  
            typeArgs[3] = Integer.TYPE;  
            Method pkgParser_parsePackageMtd = pkgParserCls.getDeclaredMethod("parsePackage",  
                    typeArgs);  
            valueArgs = new Object[4];  
            valueArgs[0] = new File(apkPath);  
            valueArgs[1] = apkPath;  
            valueArgs[2] = metrics;  
            valueArgs[3] = 0;  
            Object pkgParserPkg = pkgParser_parsePackageMtd.invoke(pkgParser, valueArgs);  
            // 应用程序信息包, 这个公开的, 不过有些函数, 变量没公开  
            // ApplicationInfo info = mPkgInfo.applicationInfo;  
            Field appInfoFld = pkgParserPkg.getClass().getDeclaredField("applicationInfo");  
             info = (ApplicationInfo) appInfoFld.get(pkgParserPkg);  
            // uid 输出为"-1"，原因是未安装，系统未分配其Uid。  
            LogUtil.d("fileAppFrag", "pkg:" + info.packageName + " uid=" + info.uid);
            // Resources pRes = getResources();  
            // AssetManager assmgr = new AssetManager();  
            // assmgr.addAssetPath(apkPath);  
            // Resources res = new Resources(assmgr, pRes.getDisplayMetrics(),  
            // pRes.getConfiguration());  
            Class assetMagCls = Class.forName(PATH_AssetManager);  
            Constructor assetMagCt = assetMagCls.getConstructor((Class[]) null);  
            Object assetMag = assetMagCt.newInstance((Object[]) null);  
            typeArgs = new Class[1];  
            typeArgs[0] = String.class;  
            Method assetMag_addAssetPathMtd = assetMagCls.getDeclaredMethod("addAssetPath",  
                    typeArgs);  
            valueArgs = new Object[1];  
            valueArgs[0] = apkPath;  
            assetMag_addAssetPathMtd.invoke(assetMag, valueArgs);  
            Resources res = getResources();  
            typeArgs = new Class[3];  
            typeArgs[0] = assetMag.getClass();  
            typeArgs[1] = res.getDisplayMetrics().getClass();  
            typeArgs[2] = res.getConfiguration().getClass();  
            Constructor resCt = Resources.class.getConstructor(typeArgs);  
            valueArgs = new Object[3];  
            valueArgs[0] = assetMag;  
            valueArgs[1] = res.getDisplayMetrics();  
            valueArgs[2] = res.getConfiguration();  
            res = (Resources) resCt.newInstance(valueArgs);  
            CharSequence label = null;  
            if (info.labelRes != 0) {  
                label = res.getText(info.labelRes);  
            }  
            // if (label == null) {  
            // label = (info.nonLocalizedLabel != null) ? info.nonLocalizedLabel  
            // : info.packageName;  
            // }  
            LogUtil.d("fileAppFrag", "label=" + label);  
            // 这里就是读取一个apk程序的图标  
            if (info.icon != 0) {  
                // icon = res.getDrawable(info.icon);  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return info;
    }  
}
